/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core;

import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import com.googlecode.actorom.Actor;
import com.googlecode.actorom.support.ActorInvocationException;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class CoreActor implements Actor {

    private static final transient Logger LOG = LoggerFactory.getLogger(CoreActor.class);
    private final CoreProcess process;
    private final MessageQueue mailbox;

    public CoreActor(CoreProcess process, MessageQueue mailbox) {
        this.process = process;
        this.mailbox = mailbox;
    }

    public void send(Object message) throws ActorInvocationException {
        if (process.isActive()) {
            try {
                mailbox.put(new MessageHandle(process.getAddress(), message));
            } catch (InterruptedException ex) {
                LOG.warn("Unable to send message to actor at address {}", process.getAddress());
                throw new ActorInvocationException(ex.getMessage(), ex);
            }
        } else {
            throw new ActorInvocationException("The actor at address " + process.getAddress() + " is killed!");
        }
    }

    public CoreProcess getProcess() {
        return process;
    }

    public MessageQueue getMailbox() {
        return mailbox;
    }
}
